<?php
// greencuisine

$con = mysql_connect("localhost","greencuisine",'greencui$ine');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("greencuisine", $con);

// MySQL Quotes Safe Guard
function quote($value) {
   // Stripslashes
   if(get_magic_quotes_gpc()) {
       $value = stripslashes($value);
   }
   // Quote if not integer
   if(!is_numeric($value)) {
       //$value = "'" . mysql_real_escape_string($value) . "'";
       $value = mysql_real_escape_string($value);
   }
   return $value;
}

if(isset($_POST['green']) && isset($_POST['cuisine']) && isset($_POST['offset']) && isset($_POST['limit'])) {
	$_POST['green'] = quote($_POST['green']);
	$_POST['cuisine'] = quote($_POST['cuisine']);
	$_POST['offset'] = quote($_POST['offset']);
	$_POST['limit'] = quote($_POST['limit']);
	$i = 0;
	
	$result_query = "SELECT * FROM restaurants WHERE geocoded = 1 ";
	if(!empty($_POST['cuisine'])) { $result_query .= "AND cuisine = '".$_POST['cuisine']."' "; }
	if(!empty($_POST['green'])) { $result_query .= "AND green = '".$_POST['green']."' "; }
	$result_query .= "ORDER BY name LIMIT ".$_POST['limit']." OFFSET ".$_POST['offset'];
	
	$count_query = "SELECT COUNT(*) FROM restaurants WHERE geocoded = 1 ";
	if(!empty($_POST['cuisine'])) { $count_query .= "AND cuisine = '".$_POST['cuisine']."' "; }
	if(!empty($_POST['green'])) { $count_query .= "AND green = '".$_POST['green']."' "; }
	
	$count = mysql_query($count_query);
	
	$results = mysql_query($result_query);
	
	while($row = mysql_fetch_array($count)) {
		$total_num = $row[0];
	}
	$json_string = $total_num."|[";
	
	$total = mysql_num_rows($results);
	while($row = mysql_fetch_array($results))
	  {
	  $i++;
	  $json_string .= "{'id': '".$i."', 'name': '".$row['name']."', 'address1': '".$row['address1']."', 'address2': '".$row['address2']."', 'phone': '".$row['phone']."', 'green': '".$row['green']."', 'hours': '".$row['hours']."', 'specialties': '".$row['specialties']."', 'website': '".$row['website']."', 'cuisine': '".$row['cuisine']."', 'lat': '".$row['lat']."', 'lng': '".$row['lng']."'}";
	  if($i < $total) { $json_string .= ","; }
	  }	
	$json_string .= "]";
	$json_string = preg_replace('/\s\s+/', ' ', $json_string);
	echo $json_string;
	
}
else echo "error";
?>
